//
//  GridViewController.m
//  Grid
//
//  Created by lee jory on 09-10-22.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "ListController.h"
#import "MServerDAO.h"
#import "MCFunction.h"
#import "MClientAppDelegate.h"
#import "QueryController.h"
#import "MCUIToolkit.h"
#import "EGORefreshTableHeaderView.h"
#import "WithFormButtonsBar.h"

@interface ListController (Private)
- (void) loadData;
@end

@implementation ListController
@synthesize dataObjectName;
@synthesize layoutName;
@synthesize queryFilter;
@synthesize page;
@synthesize listData;
@synthesize listLayout;
@synthesize dataRefresh;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

	[super viewDidLoad];
	
	self.title = [listLayout objectForKey:@"lbl"];
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	
	isJump2Page = ![[[listLayout objectForKey:@"csty"] objectForKey:@"scroll2page"] intValue];
	isFirstColumnFixed = [[[listLayout objectForKey:@"csty"] objectForKey:@"firstcolumn"] intValue];
	buttonCol = 1;
	if ([listLayout objectForKey:@"csty"]) {
		if ([[listLayout objectForKey:@"csty"] objectForKey:@"button_col"]) {
			buttonCol =  [[[listLayout objectForKey:@"csty"] objectForKey:@"button_col"] intValue];
			if (buttonCol > 3) {
				buttonCol = 3;
			}
		}
	}
	if (isJump2Page) {
		pageBar = [MCUIToolkit getPageBar:[MCUIToolkit hasQueryField:listLayout] delegate:self];
		[self.clientView addSubview:pageBar];
		pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
		pageBar.autoresizingMask = nMCViewAutoresizingMask;
		pageBar.hidden = YES;
	}
	isMsel = [[listLayout objectForKey:@"msel"] boolValue];
	if (isMsel) {
		isFirstColumnFixed = NO;
	}
	valueBufferArray = [[NSMutableArray alloc] init];
	// 根据配置显示/隐藏帮助按钮
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter04.html";
	page = 1;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self didRotateFromInterfaceOrientation:0];
}

- (void)dealloc {
	[pageBar release];
	[dataObjectName release];
	[layoutName release];
	[queryFilter release];
	[listData release];
	[listLayout release];
	if (listCell) {
		[listCell removeFromSuperview];
		[listCell release];
	}
	
	[listButtons release];
	[withFormButtons release];
	[valueBufferArray release];
    [super dealloc];
}

#pragma mark ---UIToolbar事件---
-(void)goFirst:(id)inSender {
	dataRefresh = NO;
	if (page != 1) {
		page = 1;
		[self getDataFromServer];
	}
}

-(void)goPrevious:(id)inSender {
	dataRefresh = NO;
	if (page > 1) {
		page = page - 1;
		[self getDataFromServer];
	}
}

-(void)goNext:(id)inSender {
	dataRefresh = NO;
	if (page < totalPage) {
		page = page + 1;
		[self getDataFromServer];
	}
}

-(BOOL)getNextData {
	dataRefresh = NO;
	if (page < totalPage) {
		page = page + 1;
		[self getDataFromServer];
		return YES;
	} else {
		return NO;
	}
}
-(BOOL)getPreviousData {
	dataRefresh = NO;
	if (page > 1) {
		page = page - 1;
		[self getDataFromServer];
		return YES;
	} else {
		return NO;
	}
}

-(void)goLast:(id)inSender {
	dataRefresh = NO;
	if (page != totalPage) {
		page = totalPage;
		[self getDataFromServer];
	}
}

-(void)gotoPage:(id)inSender {
	dataRefresh = NO;
	UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
	int goPage = [inputView.text intValue];
	if (goPage >= 1 && goPage <= totalPage) {
		page = goPage;
		[self getDataFromServer];
	}
}

-(void)reload:(id)inSender {
	dataRefresh = NO;
	[self getDataFromServer];
}

-(void)search:(id)inSender {
	QueryController *queryController = [[QueryController alloc] initWithStyle:UITableViewStylePlain];
	queryController.listLayout = self.listLayout;
	queryController.queryFilter = self.queryFilter;
	queryController.queryFirst = NO;
	[self.navigationController pushViewController:queryController animated:YES];
	[queryController release];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	if (dataRefresh && !isJump2Page) {
		page = 1;
	}
	[(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1] resignFirstResponder];
	[valueBufferArray removeAllObjects];
	[[MServerDAO sharedInstance] getListDataAsync:dataObjectName 
									   layoutName:layoutName 
									  queryFilter:queryFilter 
											 page:page
										 delegate:self];
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if (isJump2Page || [MCUserDefaults instance].dragListLastAndMore) {
		self.listData = [returnValue objectForKey:@"rl"];
	} else {
		if (self.listData == nil) {
			self.listData = [NSMutableArray arrayWithArray:[returnValue objectForKey:@"rl"]];
		} else {
			[self.listData addObjectsFromArray:[returnValue objectForKey:@"rl"]];
		}
	}
	
	if (dataRefresh && !isJump2Page) {
		[self.listData removeAllObjects];
		self.listData = [returnValue objectForKey:@"rl"];
	}
	
	totalPage = 1;
	if ([returnValue objectForKey:@"tp"]) {
		totalPage = [[returnValue objectForKey:@"tp"] intValue];
	}
	if (totalPage == 0) {
		totalPage = 1;
	}
	
	if (totalPage < 2 && pageBar) {
		[pageBar removeFromSuperview];
		[pageBar release];
		pageBar = nil;
	} else {
		pageBar.hidden = NO;
	}
	
	if (pageBar && [pageBar.items count] > 5) {
		UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
		inputView.text = @"";
		inputView.placeholder = [NSString stringWithFormat:@"%d", page];
		UILabel *pageLabel = (UILabel *)(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:2];
		pageLabel.text = [NSString stringWithFormat:@"/%d", totalPage];
	}
	NSMutableArray *dataButtons = [returnValue objectForKey:@"btn"];
	NSMutableArray *cfgButtons = [listLayout objectForKey:@"btn"];
	if (listButtons) {
		[listButtons release];listButtons = nil;
	}
	listButtons = [[MCUIToolkit getButtons:dataButtons cfgButtons:cfgButtons] retain];	
	withFormButtons = [MCUIToolkit getWithFormButtons:listButtons];
	
	[self rightBarButton:@"操作" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
	if ([listButtons count] == 1) {
		self.rightBarButtonItemTitle = [[listButtons objectAtIndex:0] objectForKey:@"lbl"];
	} else if ([listButtons count] > 1) {
		self.rightBarButtonItemTitle = @"操作";
	} else {
		self.rightBarButtonItem = nil;
	}
	if ([returnValue objectForKey:@"csty"]) {
		NSMutableDictionary *csty = [returnValue objectForKey:@"csty"];
		if ([csty objectForKey:@"label"]) {
			self.title = [csty objectForKey:@"label"];
		}
	}
	if ([self.view viewWithTag:-963]) {
		[[self.view viewWithTag:-963] removeFromSuperview];
	}
	if ([self.listData count] == 0) {
		UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds];
		label.text = @"当前无数据！";
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		label.tag = -963;
		[self.view addSubview:label];
		[label release];
	}
	[self loadData];
}

- (void)loadData{//刷新界面？huotianjun
	DataGridComponentDataSource *ds = [[DataGridComponentDataSource alloc] init];
	NSMutableArray *titleWidth = [NSMutableArray array];
	NSMutableArray *titleLabel = [NSMutableArray array];
	NSMutableArray *fieldTypes = [NSMutableArray array];
	if (isMsel) {
		NSString *t = [NSString stringWithFormat:@"%d",48];
		[titleWidth addObject:t];
		[titleLabel addObject:@""];
		[fieldTypes addObject:@""];
	}
	int itemCount = 0;
	NSMutableArray *listFields = [listLayout objectForKey:@"item"];
	for(int i = 0;i < [listFields count];i++) {
		if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
			itemCount++;
		}
	}
	int j = -1;
	for(int i = 0;i < [listFields count];i++) {
		if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
			NSString *label = [MCUIToolkit getFieldLabel:[listFields objectAtIndex:i]];
			if ([self.listData count] > 0) {
				NSMutableDictionary *style = [MCUIToolkit getFieldTextStyle:[self.listData objectAtIndex:0] appItem:[listFields objectAtIndex:i]];
				if (style != nil) {
					if ([style objectForKey:@"label_color"]) {
						NSString *label_color = [style objectForKey:@"label_color"];
						label = [NSString stringWithFormat:@"%@:-:%@", label, label_color];
					}
				}
			}
			[titleLabel addObject:label];
			j++;
			int length = MAX([MCUIToolkit getFieldLength:[listFields objectAtIndex:i]]*8.0, 
							 [MCUIToolkit getMaxWidth:self.listData withAppItems:[listFields objectAtIndex:i]]);
//			if (itemCount == 1){
//				length = 40;
//			}
//			if (itemCount == 2){
//				length = 40 / 2;
//			}
//			if (length == 0) {
//				length = 15;
//			}
//			length = length * 8;
			if ([self.listData count] > 0) {
				NSMutableDictionary *style = [MCUIToolkit getFieldTextStyle:[self.listData objectAtIndex:0] appItem:[listFields objectAtIndex:i]];
				if (style != nil) {
					if ([style objectForKey:@"width"]) {
						length = [[style objectForKey:@"width"] intValue];
						length = self.width*length/100.0;
					}
				}
			}
			NSString *len = [NSString stringWithFormat:@"%d",length];
			NSString *fieldType = [MCUIToolkit getFieldType:[listFields objectAtIndex:i]];
			[titleWidth addObject:len];
			[fieldTypes addObject:fieldType];
		}
	}
	ds.columnWidth = titleWidth;
	ds.titles = titleLabel;
	ds.fieldTypes = fieldTypes;
	
	NSMutableArray *tableValue = [NSMutableArray array];
	//填充数据=============
	for (NSMutableDictionary *record in self.listData) {
		NSMutableArray *rowData = [[NSMutableArray alloc] init];
		if (isMsel) {
			[rowData addObject:@""];
		}
		for (int i = 0;i < [listFields count]; i++) {
			if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
				NSString *strValue = [MCUIToolkit getFieldTextValue:record appItem:[listFields objectAtIndex:i] selectOption:nil];
				NSMutableDictionary *style = [MCUIToolkit getFieldTextStyle:record appItem:[listFields objectAtIndex:i]];
				if (style != nil) {
					if ([style objectForKey:@"font_color"]) {
						NSString *font_color = [style objectForKey:@"font_color"];
						strValue = [NSString stringWithFormat:@"%@:-:%@", strValue, font_color];
					}
				}
				[rowData addObject:strValue];
			}
		}
		[tableValue addObject:rowData];
		[rowData release];
	}
	ds.data = tableValue;
	
	if (listCell != nil) {
		[listCell removeFromSuperview];
		[listCell release];
		listCell = nil;
	}
	int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
	WithFormButtonsBar *withFormButtonsBar = nil;
	if (pageBar) {
		pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
		listCell = [[[[MCUserDefaults instance] class:@"ListCell"] alloc] initWithFrame:CGRectMake(0, 0, self.width, CGRectGetMinY(pageBar.frame)-withFormButtonsBarHeight)
												   data:ds
											   gridType:@"L" 
											  totalPage:0 
											currentPage:0
									 isFirstColumnFixed:isFirstColumnFixed
												 isMsel:isMsel];
		withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(pageBar.frame)-withFormButtonsBarHeight, self.width, withFormButtonsBarHeight)];
	} else {
		listCell = [[[[MCUserDefaults instance] class:@"ListCell"] alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height-withFormButtonsBarHeight)
												   data:ds
											   gridType:@"L" 
											  totalPage:totalPage 
											currentPage:page
									 isFirstColumnFixed:isFirstColumnFixed
												 isMsel:isMsel];
		withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, self.height-withFormButtonsBarHeight, self.width, withFormButtonsBarHeight)];
	}
	if (withFormButtonsBarHeight == 0) {
		[withFormButtonsBar release];
	} else {
		WithFormButtonsBar *buttonsBar = (WithFormButtonsBar *)[self.clientView viewWithTag:-8888];
		if (buttonsBar) {
			[buttonsBar removeFromSuperview];
		}
		withFormButtonsBar.tag = -8888;
		[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
		[self.clientView addSubview:withFormButtonsBar];
		[withFormButtonsBar release];
	}

	listCell.dataObjectName = self.dataObjectName;
	listCell.layoutName = self.layoutName;
	listCell.listLayout = self.listLayout;
	listCell.listData = self.listData;
	listCell.viewController = self;
	listCell.valueBufferArray = valueBufferArray;
	[ds release];
	[self.clientView addSubview:listCell];
}

- (void)withFormButtonsAction:(id) sender {
	NSMutableDictionary *button = [withFormButtons objectAtIndex:((UIButton *)sender).tag];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	NSMutableDictionary *url = [button objectForKey:@"url"];
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId,@"buttonId",
									   @"list_form",@"buttonType",
									   self.dataObjectName,@"dataObjectName",nil];
	if (isMsel) {
		[parameters setObject:valueBufferArray forKey:@"recordArray"];
	}
	if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
		[MCFunction pushViewByUrl:url	
					   parameters:parameters
				   confirmMessage:[button objectForKey:@"cfmi"] 
				   naviController:self.navigationController];
	}else {
		[MCFunction pushViewByUrl:url	
					   parameters:parameters
				   confirmMessage:nil 
				   naviController:self.navigationController];
	}
	[parameters release];	
}


//导航栏上动作按钮的点击事件
- (void) selectAction: (id) sender {
	if ([listButtons count] == 1) {
		NSMutableDictionary *button = [listButtons objectAtIndex:0];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];		
		NSMutableDictionary *url = [button objectForKey:@"url"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"list_form",@"buttonType",
										   self.dataObjectName,@"dataObjectName",nil];
		if (isMsel) {
			[parameters setObject:valueBufferArray forKey:@"recordArray"];
		}
		if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
			[MCFunction pushViewByUrl:url	
						   parameters:parameters
					   confirmMessage:[button objectForKey:@"cfmi"] 
					   naviController:self.navigationController];
		}else {
			[MCFunction pushViewByUrl:url	
						   parameters:parameters
					   confirmMessage:nil 
					   naviController:self.navigationController];
		}
		[parameters release];
		return;
	}

	UIActionSheet *menu = [MCUIToolkit actionSheet:listButtons
										   withTag:0
									  withDelegate:self
										 withTitle:@"选择操作"];
	[menu showFromTabBar:(UITabBar *)[self.navigationController view]];
}


- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {	
	if (buttonIndex == [listButtons count]) {
		// 按下取消按钮
		return;
	}
	NSMutableDictionary *button = [listButtons objectAtIndex:buttonIndex];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	NSMutableDictionary *url = [button objectForKey:@"url"];
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										buttonId,@"buttonId",
										@"list_form",@"buttonType",
										self.dataObjectName,@"dataObjectName",nil];
	if (isMsel) {
		[parameters setObject:valueBufferArray forKey:@"recordArray"];
	}
	if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
		[MCFunction pushViewByUrl:url	
					   parameters:parameters
				   confirmMessage:[button objectForKey:@"cfmi"] 
				   naviController:self.navigationController];
	}else {
		[MCFunction pushViewByUrl:url	
					   parameters:parameters
				   confirmMessage:nil 
				   naviController:self.navigationController];
	}
	[parameters release];
}


- (void) selectCancelAction: (id) sender {
	
	UIViewController *viewController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
	if ([viewController isMemberOfClass:[QueryController class]]){
		[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 3] animated:YES];
		return;
	}
	[self.navigationController popViewControllerAnimated:YES];
}


- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	
	[self loadData];
}

@end
